<?php
/**
 * Created by PhpStorm.
 * User: lzhy@lzhy.me
 * Date: 2019/2/28 0028
 * Time: 16:17
 */
namespace Api\Event;

class WechatPayEvent
{
    private static $appId;
    private static $appSecret;
    private static $key;
    private static $mch_id;
    private static $notifyUrl;
    private static $payParamsStr;

    function __construct($appId,$appSecret,$key,$mch_id,$notifyUrl)
    {
        self::$appId = $appId;
        self::$appSecret = $appSecret;
        self::$key = $key;
        self::$mch_id = $mch_id;
        self::$notifyUrl = $notifyUrl;
    }

    /**
     * 统一下单
     * @param $openId
     * @param $money
     * @param $order
     * @param $body
     * @param array $outParams
     * @return mixed
     */
    public function unifiedOrder($openId,$money,$order,$body,$outParams = [])
    {
        $params = array_filter(array_merge(ToolEvent::unifiedOrderDefaultParams(
            self::$appId,self::$mch_id,$openId,self::$notifyUrl
        ),[
            'body'         => $body,
            'total_fee'    => $money,
            'out_trade_no' => $order
        ],$outParams));
        $params['sign'] = ToolEvent::weChatMd5Sign($params,self::$key);
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        $result = ToolEvent::curlPost($url,ToolEvent::arr2xml($params));
        return $result;
    }

    /**
     * @param $money
     * @param $order
     * @param string $body
     * @param array $outParams
     * @return $this
     */
    public function jsPay($money,$order,$body = '充值',$outParams = [])
    {
        $openId = WechatEvent::getUserOpenId(self::$appId,self::$appSecret);
        $result = $this->unifiedOrder($openId,$money,$order,$body,$outParams);
        $result = ToolEvent::xml2arr($result);
        self::$payParamsStr = WechatJsPayEvent::buildParamsStr(self::$appId,self::$key,$result['prepay_id']);
        return $this;
    }

    /**
     *
     * @return mixed
     */
    public function getParams()
    {
        return self::$payParamsStr;
    }

    /**
     * 展示js_pay页面
     * @param $jumpUrl
     * @param bool $debug
     */
    public function view($jumpUrl,$debug = false)
    {
        exit(WechatJsPayEvent::html(self::$payParamsStr,$jumpUrl,$debug));
    }
}